<?php
/**
 * 文章模块
 * 
 + ----------------------------------------------------- 
 * Date 2013-3-8
 + -----------------------------------------------------
 */
class ArticleAction extends CommonAction {
	
	public function __construct() {
		parent::__construct();
		$this->model=M("Article");
	}
	
	public function add() {
		$mid=isset($_REQUEST['mid']) ? intval($_REQUEST['mid']) : 0;
		
		$menu_model=D('Menu');
		$menus=$menu_model->getSubmenu(0,$mid);
		$this->assign('menus', $menus);
		// 当前栏目
		$current_menu=$menu_model->table(C('DB_PREFIX').'menu as m')
								->join('left join '.C('DB_PREFIX').'menu_type as t on(m.type_id=t.id)')
								->field('m.*,t.model')
								->where('m.id='.$mid)
								->find();
		$this->assign('current_menu', $current_menu);
		
		//查询学校字段
		if($current_menu['model']=='School'){
			$model=M('SchoolType');
			$this->assign('school_types',$model->getField('id,name'));
			$model=M('SchoolArea');
			$this->assign('school_areas',$model->getField('id,name'));
			$model=M('SchoolTime');
			$this->assign('school_times',$model->getField('id,name'));
			$model=M('SchoolFee');
			$this->assign('school_fees',$model->getField('id,name'));
			$model=M('SchoolRoom');
			$this->assign('school_rooms',$model->getField('id,name'));
		}
        $this->display();
    }
	
	public function insert() {
		if(IS_POST){
			$model = D('Article');
			if (false === $model->create()) {
				$this->error($model->getError());
			}
			//若有上传文件
			if(!empty($_FILES['image']['name'])){
				//图片上传 自定义目录
				$info=$this->_upload($this->getSavePath($_FILES['image']['name']),true,C('SITE_THUMB_WIDTH'),C('SITE_THUMB_HEIGHT'),true);
				//图片存入
				$model->image = $image = isset($info[0]['savename']) ? $info[0]['savepath'].$info[0]['savename']: '';
			}else{
				//$this->error('请上传图片');
			}
			if (false !== $record_id=$model->add()) {
				//保存附件信息
				$Attach=M("Attach");
				$data=array(
						'record_id'	=> 	$record_id,
						'path'		=> 	$image,
						'model' 	=> 	MODULE_NAME,
						'size'		=> 	getFileSize($image),
						'add_time'	=>	time()
				);
				if(isset($image)){
					$Attach->data($data)->add();
				}
				// 保存标签与记录
				// $this->saveTag(trim($_POST['tags']),$result);
				$this->success(L('添加成功！'),$this->getReturnUrl());
			} else {
				$this->error(L('添加失败！'));
			}
		}else{
			$this->error(L('非法操作！'));
		}
    }
	
    public function edit() {
    	$mid=isset($_REQUEST['mid']) ? intval($_REQUEST['mid']) : 0;
    	
        $id = $_REQUEST[$this->model->getPk()];
        $data = $this->model->find($id);
        $this->assign('data', $data);
         
		$menu_model=D('Menu');
		$menus=$menu_model->getSubmenu(0,$data['menu_id']);
		$this->assign('menus', $menus);
		// 当前栏目
		$current_menu=$menu_model->table(C('DB_PREFIX').'menu as m')
								->join('left join '.C('DB_PREFIX').'menu_type as t on(m.type_id=t.id)')
								->field('m.*,t.model')
								->where('m.id='.$mid)
								->find();
		$this->assign('current_menu', $current_menu);
		
    	//查询学校字段
		if($current_menu['model']=='School'){
			$model=M('SchoolType');
			$this->assign('school_types',$model->getField('id,name'));
			$model=M('SchoolArea');
			$this->assign('school_areas',$model->getField('id,name'));
			$model=M('SchoolTime');
			$this->assign('school_times',$model->getField('id,name'));
			$model=M('SchoolFee');
			$this->assign('school_fees',$model->getField('id,name'));
			$model=M('SchoolRoom');
			$this->assign('school_rooms',$model->getField('id,name'));
		}
        $this->display('add');
    }
	
	public function update() {
        if(IS_POST){
        	$model = D('Article');
        	$art=$model->getById($_POST['id']);
			if (false === $model->create()) {
				$this->error($model->getError());
			}
			//若有上传信息
			if(!empty($_FILES['image']['name'])){
				$info=$this->_upload($this->getSavePath($_FILES['image']['name']),true,C('SITE_THUMB_WIDTH'),C('SITE_THUMB_HEIGHT'),true);
				if(isset($info[0]['savename'])){
					//成功后删除原来图片
					@unlink($art['image']);
					$model->image = $image = $info[0]['savepath'].$info[0]['savename'];
				}else{
					$model->image = $image=	$art['image'];
				}
			}else{
				$model->image = $image = $art['image'];
			}
			$result = $model->save();
			if ($result) {
				//更新附件信息
				$Attach=M("Attach");
				$data['record_id']=intval($_POST['id']);
				$data['path']=$image;
				$data['model']=MODULE_NAME;
				$data['size']=getFileSize($image);
				$data['add_time']=time();
				if(isset($image) && $image != $art['image']){
					//删除原附件
					if($this->_delAttach($_POST['id'])){
						//插入新附件
						$Attach->data($data)->add();
					}
				}
				//保存标签与记录
				//$this->saveTag(trim($_POST['tags']),intval($_POST['id']));
				$this->success(L('编辑成功！'),$this->getReturnUrl());
			} else {
				$this->error(L('编辑失败！'));
			}
		}else{
			$this->error(L('非法操作！'));
		}
    }
    
    /**
     * ajax删除文章操作，包括附件
     */
    public function ajax_delete() {
    	//删除指定记录
    	$model = D("Article");
    	if (!empty($model)) {
    		$pk = $model->getPk();
    		$id = $_REQUEST ['id'];
    		if (isset($id)) {
    			$condition = array(
    					$pk => array('in', explode(',', $id)),
    			);
    			if (false !== $model->where($condition)->delete()) {
    				//删除评论
    				$Comment=M('Comment');
    				$where=array(
    					'record_id' =>	array('in', explode(',', $id)),
    					'model'		=>	MODULE_NAME
    				);
    				$Comment->where($where)->delete();
    				//删除附件
    				$Attach=M("Attach");
    				$condition=array(
    						'record_id' =>	array('in', explode(',', $id)),
    						'model'		=>	MODULE_NAME
    				);
    				$images=$Attach->where($condition)->select();
    				if(count($images)>0){
    					foreach ($images as $v){
    						@unlink($v['path']);
    					}
    				}
    				$Attach->where($condition)->delete();
    				$this->ajaxReturn(1,'删除成功！',1);
    			} else {
    				$this->ajaxReturn(0,'删除失败！',0);
    			}
    		} else {
    			$this->ajaxReturn(0,'非法操作！',0);
    		}
    	}
    	$this->forward();
    }
	
	public function index() {
		$mid=isset($_REQUEST['mid']) ? intval($_REQUEST['mid']) : 0 ;
		$order=isset($_REQUEST['order']) ? 'a.'.$_REQUEST['order'] :'';
		$sort=isset($_REQUEST['sort'])&&$_REQUEST['sort']=='asc' ? true :false;
		//当前栏目
		$menu_model=D("Menu");
		//$curr_menu=$menu_model->getById($mid);
		//$this->assign("curr_menu",$curr_menu);
		//所有栏目
		$all_menu=$menu_model->getSubmenu(0,$mid);
		$this->assign("all_menu",$all_menu);
        //生成查询Map对象，自定义模糊查询
        $map = $this->_search();
		
		$ids=$menu_model->getSubmenuId($mid);
		array_push($ids,$mid);
		if($ids){
			$map['a.menu_id']=array('in',$ids);
		}
		
		$this->_list($this->model, $map, $order, $sort);
		
		$this->display();
    }
    
    protected function _search($name = '') {
    	//生成查询条件
    	if (empty($name)) {
    		$name = $this->getActionName();
    	}
    	$model = M($name);
    	$map = array();
    	foreach ($model->getDbFields() as $key => $val) {
    		if (substr($key, 0, 1) == '_')
    			continue;
    		if (isset($_REQUEST[$val]) && $_REQUEST[$val] != '') {
    			$like_fields=C('LIKE_MATCH_FIELDS');
    			if(!empty($like_fields)){
    				$like_fields=@explode('|',C('LIKE_MATCH_FIELDS'));
    				if(in_array($val,$like_fields)){
    					$map['a.'.$val]=array('like','%'.$_REQUEST[$val].'%');
    				}
    			}else{
    				$map['a.'.$val] = $_REQUEST[$val];
    			}
    		}
    	}
    	return $map;
    }
	
	protected function _list($model, $map = array(), $sortBy = '', $asc = false) {
		$all_fields=$model->getDbFields();
        //排序字段 默认为主键名
        if (isset($_REQUEST['order'])) {
            $order = 'a.'.$_REQUEST['order'];
        } else {
            $order = !empty($sortBy) ? 'a.'.$sortBy : 'a.'.$model->getPk();
        }
        //排序方式
        if (isset($_REQUEST['sort'])) {
            $sort = $_REQUEST['sort']=='asc' ? 'asc' : 'desc';
        } else {
            $sort = $asc ? 'asc' : 'desc';
        }
        //取得满足条件的记录数
        $count = $model->table(C("DB_PREFIX").'article a')
        		->join('left join '.C("DB_PREFIX").'menu m on(a.menu_id=m.id)')
		        ->field('a.id,m.menu_name')
		        ->where($map)
		        ->order($order.' '.$sort)
		        ->count("a.id");
        import("ORG.Util.Page");
        //创建分页对象 listRows 每页显示数量
        if (!empty($_REQUEST['listRows'])) {
            $listRows = $_REQUEST['listRows'];
        } else {
            $listRows = '15';
        }
        $p = new Page($count, $listRows);
        //分页查询数据
        $list=$model->table(C("DB_PREFIX").'article a')
        		->join('left join '.C("DB_PREFIX").'menu m on(a.menu_id=m.id)')
		        ->field('a.*,m.menu_name')
		        ->where($map)
		        ->order($order.' '.$sort)
		        ->limit($p->firstRow . ',' . $p->listRows)
		        ->select();
		$new_list=array();
		if(is_array($list)&&count($list)>0){
			foreach ($list as $k=>$v){
				$new_list[$k]=$v;
				$model=M('Attach');
				$where=array(
					'record_id'	=>	$v['id'],
					'is_pic'	=>	1
				);
				$new_list[$k]['pic_count']=$model->where($where)->count();
			}
		}
        //分页显示
        $page = $p->show();
        //列表排序显示
        $sort = $sort == 'desc' ? 1 : 0;
        
        //模板赋值显示
        $this->assign('listRows',$listRows);
        $this->assign('pagesize',$this->_getPageSize());
        $this->assign('list', $new_list);
        $this->assign('sort', $sort);
        $this->assign('order', $order);
        $this->assign("page", $page);
		$this->assign("map", $map);
        Cookie::set('_currentUrl_', __SELF__);
    }
    
    /**
     * 所有文章
     */
    public function alllist(){
    	$order=isset($_REQUEST['order']) ? $_REQUEST['order'] : 'add_time';
    	$sort=isset($_REQUEST['sort']) && $_REQUEST['sort']=='asc' ? true :false;
    	//生成查询Map对象，自定义模糊查询
        $map = $this->_search();
    	$this->_list($this->model, $map, $order, $sort);
    	
    	$this->display();
    }
	
}

?>